package com.gnerv.rabbitmq.agent.dispatch;

import com.gnerv.rabbitmq.agent.autoconfigure.RabbitmqAgentConfigProperties;
import com.gnerv.rabbitmq.agent.cache.ClusterCache;
import com.gnerv.rabbitmq.agent.command.ClusterCommand;
import com.gnerv.rabbitmq.agent.handler.factory.ClusterStatusExecResultHandlerFactory;
import com.gnerv.rabbitmq.agent.model.entity.ClusterStatus;
import com.gnerv.rabbitmq.agent.tools.ExecTools;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Gnerv LiGen
 */
@Service
public class DispatchClusterService extends BaseDispatchService {

    @Resource
    private RabbitmqAgentConfigProperties rabbitmqAgentConfigProperties;

//    @Scheduled(cron = "*/10 * * * * ?")
    public void clusterStatus() {
        List<RabbitmqAgentConfigProperties.NodeConfig> nodes = rabbitmqAgentConfigProperties.getNodes();
        for (RabbitmqAgentConfigProperties.NodeConfig nodeConfig : nodes) {
            String version = version(nodeConfig.toNode());
            ExecTools.ExecResult execResult = ClusterCommand.build(nodeConfig.toNode()).clusterStatus();
            ClusterStatus clusterStatus = ClusterStatusExecResultHandlerFactory.build(version, execResult).handle();
            ClusterCache.STATUS.put(clusterStatus.getName(), clusterStatus);
            addNodeName(clusterStatus);
        }
    }

    public void addNodeName(ClusterStatus clusterStatus) {
        List<String> nodeList = clusterStatus.getDisc();
        nodeList.addAll(clusterStatus.getRam());
        ClusterCache.NODE_LIST.put(clusterStatus.getName(), nodeList);
    }

}
